var custominfo;

var map = L.map('divMap').setView([7.393879232967398, 114.12841796875], 5);
var zipLayer,
    markerLayer,
    variable = $("#variable").val();

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    id: 'examples.map-20v6611k',
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
}).addTo(map);

/*Code for annotation starts here*/

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
    draw: {
        position: 'topleft',
        polygon: {
            shapeOptions: {
                color: '#B000CC'
            },
            showArea: true
        },
        polyline: {
        shapeOptions: {
                color: '#7F6036'
            },
            metric: false
        },
        circle: {
            shapeOptions: {
                color: '#662d91'
            }
        },
        rectangle: {
            shapeOptions: {
                color: '#0E1DCC'
            }
        },
        textbox: {
            shapeOptions: {
                color: '#1A7F10'
            }
        }

    },
    edit: {
        featureGroup: drawnItems
    }
});
map.addControl(drawControl);

map.on('draw:created', function (e) {
    var type = e.layerType,
        layer = e.layer;

    if (type === 'marker') {
        layer.bindPopup('A popup!');
    }

    drawnItems.addLayer(layer);
});

/*Code for annotation ends here*/

function updateColor() {
    variable = $("#variable").val();
    info.update();
    zipLayer.setStyle(style);
}

function zoomZip() {
    var zip = $("#zip").val();
    var info = {
        lat : undefined,
        long : undefined
    }
    if (zip) {
        $.each( zipdata.features, function( i, obj ) {
          if (obj.properties.GEOID10 == zip) {
            info.lat = obj.properties.INTPTLAT10;
            info.long = obj.properties.INTPTLON10;

            return false;
          }
        });

        if (info.lat && info.long) {
            drawMarker(info);
            var bounds = new L.LatLngBounds([[info.lat, info.long]]);
            map.fitBounds(bounds, {maxZoom: 10});
        }
    }
}

//var colorShow = ['#1b9e77','#addd8e','#f7fcb9']
var colorShow = 'rgb(255,204,201)';
var markColor = ['darkblue','green','red'];
var leafletIds = [];

function drawMarker(info,index) {
    //remove last zips
  var feature = {
            type: "Feature",
            geometry: {
                type: "Point",
                coordinates: [info.longitude, info.latitude]
            },
            properties: {
                name: zip,
                popupContent: zip
            }
        };


    markerLayer = L.geoJson(feature);
    //markerLayer.addTo(map);

    var result = info.total/1000000
    var markColor = {};
    if(result<1){
        markColor = 'darkblue';
    }else if(result<2){
        markColor = 'blue';
    }else if(result<3){
        markColor = 'green';
    }else if(result<4){
        markColor = 'orange';
    }else if(result<5){
        markColor = 'red';
    }


    var marker = L.marker([info.latitude,info.longitude], {icon: L.AwesomeMarkers.icon({icon: 'inbox', prefix: 'fa', markerColor: markColor}) })
        .addTo(map)
        .bindPopup(info.name_local,{className:'popUpStyle'});

        leafletIds.push(marker._leaflet_id);
        marker.on('click',function(event){
            drawCharts(event.target._leaflet_id);
        })
}

function getColor(d) {

    var color = "";
    var a = (d.id+3)%3
    //drawMarker(d.properties,a)

    return colorShow;


}

function style(feature) {
    return {
        fillColor: getColor(feature),
        weight: 1,
        opacity: 0.2,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7
    };
}

function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 3,
        dashArray: '',
        fillOpacity: 1
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    info.update(layer.feature.properties);
}

function resetHighlight(e) {
    zipLayer.resetStyle(e.target);

    info.update();
}


function onEachFeature(feature, layer) {
   /* layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
    });
    */
}


var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
    this.update();
    return this._div;
};

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
    this._div.innerHTML = '<h4>'+ variable +'</h4>' +  (props ?
        '<b>Zip Code: ' + props.GEOID10 + '</b><br />' + props[variable]
        : 'Hover over a Zip Code area');
};

info.addTo(map);

$('.leaflet-map-pane g').hover(function(){
    var lefter = $(this).offset().left;
    var toper = $(this).offset().top;
    $('.leaflet-top.leaflet-right').css('left', lefter);
    $('.leaflet-top.leaflet-right').css('top', toper);
    $('.leaflet-top.leaflet-right').css('opacity', '1');
});

function drawPieChart (data, callback) {
    callback = callback || function(){};
    //Regular pie chart example
    nv.addGraph(function() {
      var chart = nv.models.pieChart()
          .x(function(d) { return d.name })
          .y(function(d) { return d.value })
          .showLabels(true);

        d3.select('.chartArea #pieChart svg')
            .datum(data)
            .transition().duration(350)
            .call(chart);

      callback.call(this);
      return chart;
    });

}

function drawLineChart (data) {
    nv.addGraph(function() {
      var chart = nv.models.lineChart()
        .useInteractiveGuideline(true)
        ;

      chart.xAxis
        .axisLabel('')
        .tickFormat(d3.format(',r'))
        ;

      chart.yAxis
        .axisLabel('Sales')
        // .tickFormat(d3.format('.02f'))
        ;

      d3.select('.chartArea #lineChart svg')
        .datum(data)
        .transition().duration(500)
        .call(chart)
        ;

      nv.utils.windowResize(chart.update);

      return chart;
    });
}

function processLineData(d) {
    var data  = {
        "medince1": {"key":"medince1", "values":[]},
        "medince2": {"key":"medince2", "values":[]},
        "medince3": {"key":"medince3", "values":[]},
        "medince4": {"key":"medince4", "values":[]},
        "medince5": {"key":"medince5", "values":[]}
    },item;

    for(var key in d.properties){
        if(key == 'address') continue;
        for(var mKey in d.properties[key]) {
            data[mKey].values.push({
                x:parseInt(key),
                y:d.properties[key][mKey]

            });
        }
    }

    data = _.values(data);
    return data;
}

function processPieData(d) {

    var pieData = {
        "medince1": {"name":"medince1","value":0},
        "medince2": {"name":"medince2","value":0},
        "medince3": {"name":"medince3","value":0},
        "medince4": {"name":"medince4","value":0},
        "medince5": {"name":"medince5","value":0}
    };

    for(var key in d.properties) {
        if(key == 'address') continue;
        for(var mKey in d.properties[key]) {
            pieData[mKey].value += d.properties[key][mKey];
        }
    }
    return _.values(pieData);
}

function drawCharts (leafletId) {
    console.log(leafletId);
    console.log(leafletIds);
    var index = leafletIds.indexOf(leafletId);
    var data = custominfo.features[index];
    var lineChartData = processLineData(data);
    var pieChartData = processPieData(data);

    drawLineChart(lineChartData);
    drawPieChart(pieChartData);

    $('.leaflet-popup-content').css('width', '951px');

    setTimeout(function() {
        $('.chartArea').appendTo('.leaflet-popup-content');
        $('body').prepend(
            '<div class="chartArea">' +
            '    <div id="lineChart">' +
            '        <svg width="475" height="330" style="width:475px;height:330px"></svg>' +
            '    </div>' +
            '    <div id="pieChart">' +
            '        <svg width="475" height="330" style="width:475px;height:330px"></svg>' +
            '    </div>' +
            '</div>'
        );
    }, 500);

}

function drawStackedBarChart() {
    return;
    nv.addGraph(function() {
      var chart = nv.models.discreteBarChart()
          .x(function(d) { return d.label })    //Specify the data accessors.
          .y(function(d) { return d.value })
          .staggerLabels(true)    //Too many bars and not enough room? Try staggering labels.
          .tooltips(false)        //Don't show tooltips
          .showValues(true)       //...instead, show the bar value right on top of each bar.
          .transitionDuration(350);


      d3.select('#topChartArea svg')
          .datum(exampleData())
          .call(chart);

      nv.utils.windowResize(chart.update);

      return chart;
    });
    //Each bar represents a single discrete quantity.
    function exampleData() {
     return  [
        {
          key: "Cumulative Return",
          values: [
            {
              "label" : "A Label" ,
              "value" : 9.765957771107
            } ,
            {
              "label" : "B Label" ,
              "value" : 10
            } ,
            {
              "label" : "C Label" ,
              "value" : 32.807804682612
            } ,
            {
              "label" : "D Label" ,
              "value" : 196.45946739256
            } ,
            {
              "label" : "E Label" ,
              "value" : 0.19434030906893
            } ,
            {
              "label" : "F Label" ,
              "value" : 98.079782601442
            } ,
            {
              "label" : "G Label" ,
              "value" : 13.925743130903
            } ,
            {
              "label" : "H Label" ,
              "value" : 5.1387322875705
            }
          ]
        }
      ]

    }
}

function updateMockTop10() {

    var labels = $('#topChartArea ul li label')
    for(var i = 0; i < labels.length; i++){
        console.log(parseInt( $(labels[i]).text()) + 'px');
        $(labels[i]).css('width', parseInt( $(labels[i]).text())/3 + 'px');
    }
    $('#topChartArea').show();
}

$(function(){
    $.get('data/shopes.json', function(datas) {
        custominfo = datas;
        // alert(JSON.stringify(datas));
        var provinces = topojson.feature(mainLand, mainLand.objects.provinces).features;
        zipLayer = L.geoJson(provinces, {style: style, onEachFeature: onEachFeature}).addTo(map);

        $.each(custominfo.features,function(index,item){
            var info = {};
            info.latitude = item.geometry.coordinates[1];
            info.longitude = item.geometry.coordinates[0];
            info.total = item.properties['2014'].medince1 +
                item.properties['2014'].medince2 +
                item.properties['2014'].medince3 +
                item.properties['2014'].medince4 +
                item.properties['2014'].medince5;
            drawMarker(info,index)
        })
        drawStackedBarChart();
        updateMockTop10();
    })
})
